﻿Imports System.Data

Public Class SSI

    Private Const sCLSProdBIC = "CLSBUS33XXX"
    Private Const sCLSUATBIC = "CLSBUS30XXX"
    Private Const sSSI = "/SSIS/"
    Private Const sNets = "/NETS"

#Region "Properties"

    Private _BSDeliveryAgent As String
    Public Property BSDeliveryAgent() As String
        Get
            Return _BSDeliveryAgent
        End Get
        Set(ByVal value As String)
            _BSDeliveryAgent = value
        End Set
    End Property

    Private _BSIntermediary As String
    Public Property BSIntermediary() As String
        Get
            Return _BSIntermediary
        End Get
        Set(ByVal value As String)
            _BSIntermediary = value
        End Set
    End Property

    Private _BSReceivingAgent As String
    Public Property BSReceivingAgent() As String
        Get
            Return _BSReceivingAgent
        End Get
        Set(ByVal value As String)
            _BSReceivingAgent = value
        End Set
    End Property

    Private _SSDeliveryAgent As String
    Public Property SSDeliveryAgent() As String
        Get
            Return _SSDeliveryAgent
        End Get
        Set(ByVal value As String)
            _SSDeliveryAgent = value
        End Set
    End Property

    Private _SSIntermediary As String
    Public Property SSIntermediary() As String
        Get
            Return _SSIntermediary
        End Get
        Set(ByVal value As String)
            _SSIntermediary = value
        End Set
    End Property

    Private _SSReceivingAgent As String
    Public Property SSReceivingAgent() As String
        Get
            Return _SSReceivingAgent
        End Get
        Set(ByVal value As String)
            _SSReceivingAgent = value
        End Set
    End Property

    Private _SSBeneficiary As String
    Public Property SSBeneficiary() As String
        Get
            Return _SSBeneficiary
        End Get
        Set(ByVal value As String)
            _SSBeneficiary = value
        End Set
    End Property

    Private _IsCLS As Boolean
    Public Property IsCLS() As Boolean
        Get
            Return _IsCLS
        End Get
        Set(ByVal value As Boolean)
            _IsCLS = value
        End Set
    End Property

    Private _IsNet As Boolean
    Public Property IsNET() As Boolean
        Get
            Return _IsNet
        End Get
        Set(ByVal value As Boolean)
            _IsNet = value
        End Set
    End Property

    Private _CurrentTrade As Trade
    Public Property CurrentTrade() As Trade
        Get
            Return _CurrentTrade
        End Get
        Set(ByVal value As Trade)
            _CurrentTrade = value
        End Set
    End Property



#End Region

    Public Sub New()
        Me.BSDeliveryAgent = "/SSIS/"
        Me.BSIntermediary = String.Empty
        Me.BSReceivingAgent = "/SSIS/"
        Me.SSDeliveryAgent = "/SSIS/"
        Me.SSIntermediary = String.Empty
        Me.SSReceivingAgent = "/SSIS/"
        Me.SSBeneficiary = "/SSIS/"
        Me.IsCLS = False
        Me.IsNET = False
    End Sub
    Public Sub ChangeToNet()
        Me.BSDeliveryAgent = "/NETS/"
        Me.BSIntermediary = ""
        Me.BSReceivingAgent = "/NETS/"
        Me.SSDeliveryAgent = "/NETS/"
        Me.SSIntermediary = ""
        Me.SSReceivingAgent = "/NETS/"
        Me.SSBeneficiary = ""
        Me.IsCLS = False
        Me.IsNET = True
    End Sub


    Sub GetSSIs(ByVal myTrade As Trade)
        'CLS Settlement
        Me.CurrentTrade = myTrade

        If Me.CurrentTrade.Broker IsNot Nothing Then

            If Me.CurrentTrade.Broker.IsCLS AndAlso Me.CurrentTrade.CLSBypassFlag = String.Empty AndAlso Me.CurrentTrade.ValueDate > Today() Then
                Me.IsCLS = True
                'get CLS Details
                If My.Settings.bSQLSSIs Then
                    PopSQLCLSInx()
                Else
                    PopCLSInx()
                End If

            End If

            'netting
            If Not Me.IsCLS Then
                PopNetInx()
            End If

            If My.Settings.bIncludeSSIs AndAlso Me.IsNET = False AndAlso Me.IsCLS = False Then
                'regular ssis
                If My.Settings.bSQLSSIs Then
                    PopSQLSSIs()
                Else
                    PopSSIs()
                End If
            Else

            End If

        End If
        'ndf
        With Me.CurrentTrade
            For Each drNDF As dsFund.NDFDeetsRow In My.Settings.NDFDetails(0)
                If .GivenCCY = drNDF.NDFCCY OrElse .CounterCCY = drNDF.NDFCCY Then
                    .FixingDate = .ValueDate.AddDays(drNDF.FixingDays * -1)

                    If .FixingDate.DayOfWeek = DayOfWeek.Sunday Then .FixingDate.AddDays(-2)
                    If .FixingDate.DayOfWeek = DayOfWeek.Saturday Then .FixingDate.AddDays(-1)
                    'check holiday by NDF currency

                    For Each drHoliday As dsHolidays.HolidaysRow In My.Settings.Holidays(0)
                        Dim dHoliday As Date = drHoliday.HolidayDate
                        Dim sCCYs As String() = drHoliday.CCYs.Split(",")
                        If (sCCYs.Contains(.GivenCCY) OrElse sCCYs.Contains(.CounterCCY)) AndAlso _
                        Date.Compare(.FixingDate, dHoliday) = 0 Then
                            .FixingDate.AddDays(-1)
                        End If
                    Next

                    'double check for day of week change
                    If .FixingDate.DayOfWeek = DayOfWeek.Sunday Then .FixingDate.AddDays(-2)
                    If .FixingDate.DayOfWeek = DayOfWeek.Saturday Then .FixingDate.AddDays(-1)

                End If

            Next
            If Not .FixingDate = #12:00:00 AM# Then
                .FixingDate = "/VALD/" & String.Format("{0:yyyyMMdd}", .FixingDate) & "/SETC/XXX"
            End If
        End With



    End Sub

#Region "Private Methods"
    Private Sub PopSQLSSIs()
        'Dim dtSSIYesNo As dsSSIs.SSIYesNoDataTable
        Dim dtSSIDetail As dsSSIs.SSIDetailsDataTable
        Dim sBuyCCY As String = CurrentTrade.GetSideDetails("BUY").CCY
        Dim sSellCCY As String = CurrentTrade.GetSideDetails("SELL").CCY

        Using taSSIDetails As New dsSSIsTableAdapters.SSIDetailsTableAdapter
            dtSSIDetail = taSSIDetails.GetDataByBrokerAndCCYs(CurrentTrade.Broker.BrokerName, sBuyCCY, sSellCCY)
            'check for no SSI entries in SSIDetails table
            If dtSSIDetail.Count = 0 Then
                Logger.MsgLog("WARNING - " & CurrentTrade.Broker.BrokerName & " SSIs do not exist in the SSIDetails SQL Table.  Proceeding with /SSIS/ in SWIFT message.")
            ElseIf dtSSIDetail.Count < 2 Then
                'find what record is missing
                'this query should return 2 records, one for each currency.  If less than that, report back to the user which is missing
                Dim drRow As dsSSIs.SSIDetailsRow = dtSSIDetail.Rows(0)
                If drRow.Currency.ToLower = sBuyCCY Then
                    Logger.MsgLog("WARNING - " & CurrentTrade.Broker.BrokerName & " SSIs for " & sSellCCY & " do not exist in the SSIDetails SQL Table.  Proceeding with /SSIS/ in SWIFT message.")
                Else
                    Logger.MsgLog("WARNING - " & CurrentTrade.Broker.BrokerName & " SSIs for " & sBuyCCY & " not exist in the SSIDetails SQL Table.  Proceeding with /SSIS/ in SWIFT message.")
                End If
            Else
                'get currency details and populate
                Dim drBuyCCY As dsSSIs.SSIDetailsRow() = dtSSIDetail.Select("Currency = '" & sBuyCCY & "'")
                Dim drSellCCY As dsSSIs.SSIDetailsRow() = dtSSIDetail.Select("Currency = '" & sSellCCY & "'")

                Me.BSDeliveryAgent = "/ABIC/" & drBuyCCY(0).SwiftCode & "|/NAME/" & drBuyCCY(0).BankName
                Me.BSIntermediary = String.Empty
                Me.BSReceivingAgent = "/ABIC/UKWN|/NAME/UKWN"
                Me.SSDeliveryAgent = "/SSIS/"
                If Not drSellCCY(0).Intermediary = String.Empty Then
                    Me.SSIntermediary = "/ABIC/" & drSellCCY(0).Intermediary
                Else
                    Me.SSIntermediary = String.Empty
                End If
                Me.SSReceivingAgent = "/ABIC/" & drSellCCY(0).SwiftCode & "|/NAME/" & drSellCCY(0).BankName
                Me.SSBeneficiary = "/ABIC/" & Me.CurrentTrade.Broker.BrokerBIC & "|/NAME/" & drSellCCY(0).AccountName & "|/ACCT/" & drSellCCY(0).Account
            End If
        End Using

    End Sub
    Private Sub PopSSIs()
        Dim sBuyCCY As String = CurrentTrade.GetSideDetails("BUY").CCY
        Dim sSellCCY As String = CurrentTrade.GetSideDetails("SELL").CCY

        Dim drBuyCCY As dsSSI.SSIsRow() = DirectCast(Me.CurrentTrade.Broker.SSI.Select("CCY = '" & sBuyCCY & "'"), dsSSI.SSIsRow())
        Dim drSellCCY As dsSSI.SSIsRow() = DirectCast(Me.CurrentTrade.Broker.SSI.Select("CCY = '" & sSellCCY & "'"), dsSSI.SSIsRow())

        If drBuyCCY.Count = 0 Then
            Logger.MsgLog(sBuyCCY & " is not in the SSIs for for " & CurrentTrade.Broker.BrokerName & ".  Processing w/o SSIs.")
            Exit Sub
        End If
        If drSellCCY.Count = 0 Then
            Logger.MsgLog(sSellCCY & " is not in the SSIs for for " & CurrentTrade.Broker.BrokerName & ".  Processing w/o SSIs.")
            Exit Sub
        End If

        Me.BSDeliveryAgent = "/ABIC/" & drBuyCCY(0).SWIFTCode & "|/NAME/" & drBuyCCY(0).BankName
        Me.BSIntermediary = String.Empty
        Me.BSReceivingAgent = "/ABIC/UKWN|/NAME/UKWN"
        Me.SSDeliveryAgent = "/SSIS/"
        If Not drSellCCY(0).Intermediary = String.Empty Then
            Me.SSIntermediary = "/ABIC/" & drSellCCY(0).Intermediary
        Else
            Me.SSIntermediary = String.Empty
        End If
        Me.SSReceivingAgent = "/ABIC/" & drSellCCY(0).SWIFTCode & "|/NAME/" & drSellCCY(0).BankName
        Me.SSBeneficiary = "/ABIC/" & Me.CurrentTrade.Broker.BrokerBIC & "|/NAME/" & drSellCCY(0).AccountName & "|/ACCT/" & drSellCCY(0).Account

    End Sub


    Private Sub PopNetInx()
        With Me.CurrentTrade
            If .NetFlag IsNot Nothing Then
                If (.Broker.BrokerBIC.ToLower = "aimxcaabxxx" AndAlso _
                    (.NetFlag.ToLower = "net" OrElse .NetFlag.ToLower = "nets")) OrElse _
                    Left(.NetFlag, 1).ToLower = "y" OrElse Left(.NetFlag, 1).ToLower = "n" Then
                    Me.ChangeToNet()
                End If
            End If

            If (.Zone IsNot Nothing AndAlso .Zone.ToLower = "net") OrElse My.Settings.bAllNet OrElse _
            (My.Settings.bFwdToNet AndAlso Me.CurrentTrade.SptFwdFlag = "Fwd") OrElse _
            (My.Settings.bOCToNet AndAlso (Me.CurrentTrade.OCFlag IsNot Nothing AndAlso Not Me.CurrentTrade.OCFlag = String.Empty)) Then
                Me.ChangeToNet()
            End If
        End With

    End Sub

    Private Sub PopCLSInx()
        Dim sCLSBIC As String
        Dim sBuyCCY As String = CurrentTrade.GetSideDetails("BUY").CCY
        Dim sSellCCY As String = CurrentTrade.GetSideDetails("SELL").CCY
        If My.Settings.sGTSSURL.ToLower.Contains("uat") Then
            sCLSBIC = sCLSUATBIC
        Else
            sCLSBIC = sCLSProdBIC
        End If

        Dim drBuyCCY As DataRow() = CurrentTrade.Broker.CLSCCYs.Select("CCY = '" & sBuyCCY & "'")
        Dim drSellCCY As DataRow() = CurrentTrade.Broker.CLSCCYs.Select("CCY = '" & sSellCCY & "'")
        Dim drCLSFund As DataRow() = CurrentTrade.Broker.CLSAccounts.Select("Fund = '" & CurrentTrade.Fund.FundName & "'")

        If drBuyCCY.Count = 0 Then
            Logger.MsgLog(sBuyCCY & " is not in the CLS currency list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Me.IsCLS = False
        End If
        If drSellCCY.Count = 0 Then
            Logger.MsgLog(sSellCCY & " is not in the CLS currency list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Me.IsCLS = False
        End If
        If drCLSFund.Count = 0 Then
            Logger.MsgLog(CurrentTrade.Fund.FundName & " is not in the CLS fund list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Me.IsCLS = False
        End If

        If Me.IsCLS Then
            If Me.CurrentTrade.Broker.Is3rdPartySettle Then
                Me.BSDeliveryAgent = Me.CurrentTrade.Broker.ThirdPartBIC
                Me.BSIntermediary = sCLSBIC
                Me.BSReceivingAgent = drCLSFund(0).Item(1) ' custodian bic
                Me.SSDeliveryAgent = String.Empty
                Me.SSIntermediary = sCLSBIC
                Me.SSReceivingAgent = Me.CurrentTrade.Broker.ThirdPartBIC
            Else
                Me.BSDeliveryAgent = Me.CurrentTrade.Broker.CLSBIC
                Me.BSIntermediary = sCLSBIC
                Me.BSReceivingAgent = drCLSFund(0).Item(1) ' custodian bic
                Me.SSDeliveryAgent = String.Empty
                Me.SSIntermediary = String.Empty
                Me.SSReceivingAgent = sCLSBIC
            End If
            Me.SSBeneficiary = Me.CurrentTrade.Broker.CLSBIC
        End If
    End Sub

    Private Sub PopSQLCLSInx()
        Dim dtBrokers As dsSSIs.CLSBrokersDataTable
        Dim dtAccounts As dsSSIs.CLSAccountsDataTable
        Dim dtCCYs As dsSSIs.CLSCurrenciesDataTable
        Dim sCLSBIC As String
        Dim sBuyCCY As String = CurrentTrade.GetSideDetails("BUY").CCY
        Dim sSellCCY As String = CurrentTrade.GetSideDetails("SELL").CCY
        If My.Settings.sGTSSURL.ToLower.Contains("uat") Then
            sCLSBIC = sCLSUATBIC
        Else
            sCLSBIC = sCLSProdBIC
        End If

        Using taCLSBrokers As New dsSSIsTableAdapters.CLSBrokersTableAdapter
            dtBrokers = taCLSBrokers.GetDataBroker(Me.CurrentTrade.Broker.BrokerName)
        End Using

        Using taCLSAccounts As New dsSSIsTableAdapters.CLSAccountsTableAdapter
            dtAccounts = taCLSAccounts.GetDataFundCode(Me.CurrentTrade.Fund.FundName)
        End Using

        Using taCLSCCys As New dsSSIsTableAdapters.CLSCurrenciesTableAdapter
            dtCCYs = taCLSCCys.GetDataByCCY(sBuyCCY, sSellCCY)
        End Using

        If dtCCYs.Count = 0 Then
            Logger.MsgLog(sBuyCCY & " " & sSellCCY & " are not in the CLS currency list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Me.IsCLS = False
        End If

        If dtCCYs.Count = 1 Then
            If dtCCYs(0).EligibleCurrency = sBuyCCY Then
                Logger.MsgLog(sSellCCY & " is not in the CLS currency list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Else
                Logger.MsgLog(sBuyCCY & " is not in the CLS currency list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            End If
            Me.IsCLS = False
        End If

        If dtAccounts.Count = 0 Then
            Logger.MsgLog(CurrentTrade.Fund.FundName & " is not in the CLS fund list for " & CurrentTrade.Broker.BrokerName & ".  Processing as non-CLS.")
            Me.IsCLS = False
        End If

        If Me.IsCLS Then
            If Me.CurrentTrade.Broker.Is3rdPartySettle Then
                Me.BSDeliveryAgent = Me.CurrentTrade.Broker.ThirdPartBIC
                Me.BSIntermediary = sCLSBIC
                Me.BSReceivingAgent = dtAccounts(0).Custodian ' custodian bic
                Me.SSDeliveryAgent = String.Empty
                Me.SSIntermediary = sCLSBIC
                Me.SSReceivingAgent = Me.CurrentTrade.Broker.ThirdPartBIC
            Else
                Me.BSDeliveryAgent = Me.CurrentTrade.Broker.CLSBIC
                Me.BSIntermediary = sCLSBIC
                Me.BSReceivingAgent = dtAccounts(0).Custodian ' custodian bic
                Me.SSDeliveryAgent = String.Empty
                Me.SSIntermediary = String.Empty
                Me.SSReceivingAgent = sCLSBIC
            End If
            Me.SSBeneficiary = Me.CurrentTrade.Broker.CLSBIC
        End If


    End Sub
#End Region

End Class
